<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>图书馆 RAG 聊天机器人</title>
    <style>
        body {
            font-family: sans-serif;
            margin: 20px;
            background: #f5f5f5;
        }

        h2 {
            margin-bottom: 10px;
        }

        #chat {
            border: 1px solid #ccc;
            border-radius: 8px;
            background: white;
            padding: 10px;
            height: 400px;
            overflow-y: auto;
        }

        .msg {
            margin: 6px 0;
            white-space: pre-wrap;
            padding: 6px 10px;
            border-radius: 6px;
            max-width: 80%;
        }

        .user {
            color: white;
            background: #007bff;
            align-self: flex-end;
            margin-left: auto;
        }

        .bot {
            color: black;
            background: #e9ecef;
            align-self: flex-start;
            margin-right: auto;
        }

        #controls {
            margin-top: 10px;
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        textarea {
            width: 100%;
            padding: 8px;
            font-size: 14px;
            border-radius: 6px;
            border: 1px solid #ccc;
        }

        button {
            padding: 8px 16px;
            font-size: 14px;
            border: none;
            border-radius: 6px;
            background: #007bff;
            color: white;
            cursor: pointer;
        }

        button:hover {
            background: #0056b3;
        }

        .mode-select {
            margin-bottom: 8px;
        }

        #chat-container {
            display: flex;
            flex-direction: column;
        }
    </style>
</head>
<body>
<h2>📚 图书馆 RAG 聊天机器人</h2>

<div class="mode-select">
    <label><input type="radio" name="mode" value="block" checked> Block</label>
    <label><input type="radio" name="mode" value="stream"> Stream</label>
</div>

<div id="chat-container">
    <div id="chat"></div>
</div>

<div id="controls">
    <textarea id="input" rows="3" placeholder="输入你的问题，比如：推荐几本数据库的书..."></textarea>
    <button id="send">发送</button>
</div>

<script>
    const chat = document.getElementById('chat');
    const input = document.getElementById('input');
    const sendBtn = document.getElementById('send');

    function addMessage(role, text, streaming = false) {
        const div = document.createElement('div');
        div.className = `msg ${role}`;
        if (streaming) div.dataset.streaming = "1";
        div.textContent = (role === 'user' ? '你: ' : 'AI: ') + text;
        chat.appendChild(div);
        chat.scrollTop = chat.scrollHeight;
        return div;
    }

    sendBtn.onclick = async () => {
        const text = input.value.trim();
        if (!text) return;
        addMessage('user', text);
        input.value = '';

        const mode = document.querySelector('input[name="mode"]:checked').value;
        const res = await fetch('http://127.0.0.1:3000/rag-chat', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                question: text,
                stream: mode === 'stream'
            })
        });
        if (mode === 'block') {
            // Block 模式：一次性拿到结果
            const data = await res.json();
            addMessage('bot', data.message ? data.message.content : JSON.stringify(data));
        } else {
            // Stream 模式：逐块显示
            const reader = res.body.getReader();
            const decoder = new TextDecoder();
            let botDiv = addMessage('bot', '', true);

            while (true) {
                const {done, value} = await reader.read();
                if (done) break;
                try {
                    const chunk = JSON.parse(decoder.decode(value, {stream: true}));
                    botDiv.textContent += chunk.message.content;
                    chat.scrollTop = chat.scrollHeight;
                } catch (e) {
                    console.error("解析流出错", e);
                }
            }
            delete botDiv.dataset.streaming;
        }
    };
</script>
</body>
</html>
